'use client';

import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Select, Space, Modal, Form, message, Popconfirm, Row, Col, Checkbox, Typography, Tooltip } from 'antd';
import { EditOutlined, DeleteOutlined, SearchOutlined, SaveOutlined, LockOutlined, InfoCircleOutlined, UndoOutlined } from '@ant-design/icons';
import { fetchRoles, addRole, updateRole, deleteRole } from '@/lib/role';
import Layout from '@/components/Layout';
import styled from '@emotion/styled';

const { Option } = Select;
const { Title } = Typography;

const StyledCard = styled(Card)`
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
`;

const StyledTable = styled(Table)`
  .ant-table-row.selected-row {
    background-color: #e6f7ff;
    td {
      border-bottom: 2px solid #1890ff;
    }
  }
`;

const PermissionGroup = styled.div`
  background-color: #f0f2f5;
  padding: 12px;
  margin-bottom: 16px;
  border-radius: 6px;
`;

const PermissionItem = styled.div`
  margin-bottom: 8px;
`;

// 添加权限分组映射对象
const permissionGroupMap = {
  dashboard: '系统首页',
  'article-management': '文章管理',
  attendance: '考勤打卡',
  'attendance-management': '考勤管理',
  'set-check-in-time': '考勤设置',
  'leave-request': '请假申请',
  'leave-approval': '假期审批',
  'announcement-management': '公告管理',
  'admin-info': '权限管理',
  'user-info': '员工信息',
  'employee-password': '密码管理',
  'department-management': '部门管理',
  'academy-management': '学院管理',
  'other-department-management': '其它部门管理',
  onboard: '入职管理',
  'recruitment-announcements': '招聘计划审批',
  'recruitment-plan': '招聘计划管理',
  'recruitment-candidates': '应聘管理',
  'recruitment-interviews': '面试管理',
  'recruitment-analytics': '招聘分析',
  'recruitment-offer': 'Offer管理',
  'system-settings': '系统设置',
  profile: '个人信息',
  'change-password': '修改密码'
};

// 添加权限映射对象
const permissionMap = {
  // 基础权限
  dashboard: { name: '系统首页', description: '访问系统首页的权限' },
  'article-management': { name: '文章管理', description: '管理系统文章的权限' },
  attendance: { name: '考勤打卡', description: '进行考勤打卡的权限' },
  'attendance-management': { name: '考勤管理', description: '管理员工考勤记录的权限' },
  'set-check-in-time': { name: '考勤设置', description: '设置考勤规则和时间的权限' },
  'leave-request': { name: '请假申请', description: '提交请假申请的权限' },
  'leave-approval': { name: '假期审批', description: '审批员工请假申请的权限' },
  'announcement-management': { name: '公告管理', description: '管理系统公告的权限' },
  'admin-info': { name: '权限管理', description: '管理系统角色和权限的权限' },
  'user-info': { name: '员工信息', description: '查看和管理员工基本信息的权限' },
  'employee-password': { name: '密码管理', description: '管理员工账号密码的权限' },
  'department-management': { name: '部门管理', description: '管理公司部门架构的权限' },
  'academy-management': { name: '学院管理', description: '管理教学单位的权限' },
  'other-department-management': { name: '其它部门管理', description: '管理其他类型部门的权限' },
  onboard: { name: '入职管理', description: '管理新员工入职流程的权限' },
  'recruitment-announcements': { name: '招聘计划审批', description: '审批招聘计划的权限' },
  'recruitment-plan': { name: '招聘计划管理', description: '管理招聘计划的权限' },
  'recruitment-candidates': { name: '应聘管理', description: '管理应聘者信息的权限' },
  'recruitment-interviews': { name: '面试管理', description: '管理面试流程的权限' },
  'recruitment-analytics': { name: '招聘分析', description: '查看招聘数据分析的权限' },
  'recruitment-offer': { name: 'Offer管理', description: '管理录用通知的权限' },
  'system-settings': { name: '系统设置', description: '管理系统基础设置的权限' },
  profile: { name: '个人信息', description: '查看和编辑个人信息的权限' },
  'change-password': { name: '修改密码', description: '修改个人账号密码的权限' }
};

// 修改 Role 接口定义
interface Role {
  id: number;
  name: string;
  description: string;
  permissions: number[];  // 修改为 number[]
  isSystem?: boolean;
}

// 修改 Permission 接口定义
interface Permission {
  id: number;  // 修改为 number
  name: string;
  description: string;
}

const RoleManagementPage = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [allRoles, setAllRoles] = useState<Role[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [modalMode, setModalMode] = useState('add');
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [tempPermissions, setTempPermissions] = useState<number[]>([]);
  const [hasChanges, setHasChanges] = useState(false);

  useEffect(() => {
    loadRoles();
  }, []);

  useEffect(() => {
    if (selectedRole) {
      setTempPermissions(selectedRole.permissions);
      setHasChanges(false);
    }
  }, [selectedRole]);

  const loadRoles = async () => {
    setLoading(true);
    try {
      const response = await fetchRoles();
      console.log('获取到的角色和权限数据:', response.data);
      
      if (response.data && response.data.code === 1) {
        const rolesData = response.data.data.roles.map((role: any) => ({
          id: role.id,
          name: role.name,
          description: role.description,
          permissions: role.permissions.map((p: any) => p.id),
          isSystem: role.isSystem === 1
        }));
        
        const permissionsData = response.data.data.permissions || [];
        console.log('处理后的权限数据:', permissionsData);
        
        setRoles(rolesData);
        setAllRoles(rolesData);
        setPermissions(permissionsData);

        // 默认选中第一个角色
        if (rolesData.length > 0 && !selectedRole) {
          handleRoleSelect(rolesData[0]);
        }
      } else {
        throw new Error(response.data?.msg || '获取角色列表失败');
      }
    } catch (error) {
      console.error("获取角色列表失败", error);
      message.error('获取角色列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    if (!searchKeyword.trim()) {
      setRoles(allRoles);
      return;
    }
    const filteredRoles = allRoles.filter(role => 
      role.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      role.description.toLowerCase().includes(searchKeyword.toLowerCase())
    );
    setRoles(filteredRoles);
  };

  const handleReset = () => {
    setSearchKeyword('');
    setRoles(allRoles);
  };

  const showModal = (mode: 'add' | 'edit', role: Role | null = null) => {
    setModalMode(mode);
    if (mode === 'edit' && role) {
      setEditingRole(role);
      form.setFieldsValue(role);
    } else {
      setEditingRole(null);
      form.resetFields();
    }
    setModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (modalMode === 'add') {
        handleAddRole(values);
      } else {
        handleEditRole(values);
      }
    });
  };

  const handleAddRole = async (values: any) => {
    try {
      const response = await addRole(values);
      if (response.data && response.data.code === 1) {
        message.success('添加角色成功');
        setModalVisible(false);
        form.resetFields();
        loadRoles();
      } else {
        throw new Error(response.data?.msg || '添加失败');
      }
    } catch (error) {
      console.error("添加角色失败", error);
      message.error('添加角色失败: ' + error.message);
    }
  };

  const handleEditRole = async (values: any) => {
    if (!editingRole) return;

    try {
      const response = await updateRole({
        ...values,
        id: editingRole.id
      });
      if (response.data && response.data.code === 1) {
        message.success('更新角色成功');
        setModalVisible(false);
        form.resetFields();
        setEditingRole(null);
        loadRoles();
      } else {
        throw new Error(response.data?.msg || '更新失败');
      }
    } catch (error) {
      console.error("更新角色失败", error);
      message.error('更新角色失败: ' + error.message);
    }
  };

  const handleDelete = async (roleId: number) => {
    try {
      const response = await deleteRole(roleId);
      if (response.data && response.data.code === 1) {
        message.success('删除角色成功');
        loadRoles();
      } else {
        throw new Error(response.data?.msg || '删除失败');
      }
    } catch (error) {
      console.error("删除角色失败", error);
      message.error('删除角色失败: ' + error.message);
    }
  };

  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的角色');
      return;
    }

    try {
      await Promise.all(selectedRowKeys.map(id => deleteRole(id)));
      message.success('批量删除角色成功');
      loadRoles();
      setSelectedRowKeys([]);
    } catch (error) {
      console.error("批量删除角色失败", error);
      message.error('批量删除角色失败: ' + error.message);
    }
  };

  const handleRoleSelect = (role: Role) => {
    setSelectedRole(role);
    const rolePermissions = Array.isArray(role.permissions) ? role.permissions : [];
    setTempPermissions(rolePermissions);
    setHasChanges(false);
  };

  const handlePermissionChange = (permissionId: number, checked: boolean) => {
    if (selectedRole?.isSystem) {
      message.warning('系统预制角色的权限不可修改');
      return;
    }

    const newPermissions = checked 
      ? [...tempPermissions, permissionId]
      : tempPermissions.filter(id => id !== permissionId);
    
    setTempPermissions(newPermissions);
    setHasChanges(true);
  };

  const handleUndoChanges = () => {
    if (selectedRole) {
      setTempPermissions(selectedRole.permissions);
      setHasChanges(false);
    }
  };

  const handleSavePermissions = async () => {
    if (!selectedRole) return;

    if (selectedRole.isSystem) {
      message.warning('系统预制角色的权限不可修改');
      return;
    }

    try {
      const updatedRole = {
        ...selectedRole,
        permissions: tempPermissions
      };
      
      const response = await updateRole(updatedRole);
      if (response.data && response.data.code === 1) {
        message.success('更新角色权限成功');
        loadRoles();
      } else {
        throw new Error(response.data?.msg || '更新失败');
      }
    } catch (error) {
      console.error("更新角色权限失败", error);
      message.error('更新角色权限失败: ' + error.message);
      handleUndoChanges();
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: number[]) => setSelectedRowKeys(newSelectedRowKeys),
    getCheckboxProps: (record: Role) => ({
      disabled: record.isSystem,
      name: record.name,
      key: record.id.toString()
    })
  };

  const groupPermissions = () => {
    const grouped: { [key: string]: Permission[] } = {};
    
    // 遍历所有权限
    permissions.forEach(perm => {
      // 找到对应的分组
      const groupKey = Object.keys(permissionGroupMap).find(key => 
        perm.name === key
      );
      
      if (groupKey) {
        const groupName = permissionGroupMap[groupKey];
        if (!grouped[groupName]) {
          grouped[groupName] = [];
        }
        grouped[groupName].push(perm);
      }
    });
    
    return grouped;
  };

  const renderPermissionCheckboxes = () => {
    const grouped = groupPermissions();
    
    return Object.entries(grouped).map(([groupName, groupPermissions]) => (
      <PermissionGroup key={groupName}>
        <Title level={5}>{groupName}</Title>
        <Row gutter={[16, 16]}>
          {groupPermissions.map(perm => {
            const isChecked = tempPermissions.includes(perm.id);
            
            return (
              <Col key={perm.id} xs={24} sm={12} md={8} lg={6}>
                <PermissionItem>
                  <Checkbox
                    checked={isChecked}
                    onChange={(e) => handlePermissionChange(perm.id, e.target.checked)}
                    disabled={selectedRole?.isSystem}
                  >
                    {permissionMap[perm.name]?.name || perm.name}
                  </Checkbox>
                  <Tooltip title={permissionMap[perm.name]?.description || perm.description}>
                    <InfoCircleOutlined style={{ marginLeft: 8 }} />
                  </Tooltip>
                </PermissionItem>
              </Col>
            );
          })}
        </Row>
      </PermissionGroup>
    ));
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal('edit', record)}
            disabled={record.isSystem}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              disabled={record.isSystem}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Layout>
      <StyledCard title="角色管理" bordered={false}>
        <Row gutter={16}>
          <Col span={8}>
            <Space style={{ marginBottom: 16 }}>
              <Input
                placeholder="搜索角色"
                value={searchKeyword}
                onChange={e => setSearchKeyword(e.target.value)}
                style={{ width: 200 }}
              />
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
            <StyledTable
              columns={columns}
              dataSource={roles}
              rowKey={(record: Role) => record.id.toString()}
              rowSelection={rowSelection}
              onRow={(record: Role) => ({
                onClick: () => handleRoleSelect(record),
                className: record.id === selectedRole?.id ? 'selected-row' : ''
              })}
            />
            <Space style={{ marginTop: 16 }}>
              <Button type="primary" onClick={() => showModal('add')}>
                添加角色
              </Button>
              <Button danger onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
                批量删除
              </Button>
            </Space>
          </Col>
          <Col span={16}>
            <StyledCard 
              title={`角色权限 - ${selectedRole?.name || ''}`}
              extra={
                <Space>
                  <Button 
                    onClick={handleUndoChanges}
                    icon={<UndoOutlined />}
                    disabled={!hasChanges}
                  >
                    撤销更改
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<SaveOutlined />} 
                    onClick={handleSavePermissions}
                    disabled={!selectedRole || selectedRole.isSystem || !hasChanges}
                  >
                    保存权限
                  </Button>
                </Space>
              }
              bordered={false}
            >
              {renderPermissionCheckboxes()}
            </StyledCard>
          </Col>
        </Row>
      </StyledCard>

      <Modal
        title={modalMode === 'add' ? '添加角色' : '编辑角色'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入角色描述' }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            name="permissions"
            label="权限"
            rules={[{ required: true, message: '请选择权限' }]}
          >
            <Select mode="multiple">
              {permissions.map(permission => (
                <Option key={permission.id} value={permission.id}>
                  {permissionMap[permission.name]?.name || permission.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default RoleManagementPage;
